﻿package net.wangit.support.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;

import javax.servlet.http.HttpServletResponse;

import net.wangit.Path;
import net.wangit.context.ActionContext;
import net.wangit.framework.config.MimeSettings;
import net.wangit.framework.util.ResponseWriter;
import net.wangit.util.StringUtil;


/**
 * 从request中读取“url”参数，按此路径下载文件。 
 * 
 * @author watson
 * Feb 25, 2010
 */
public class URLDownloadAction extends DownloadAction {

	public URLDownloadAction() {
	}

	//下载接口。
	protected void doDownload(ActionContext ac, HttpServletResponse response)
			throws Exception {
		String path;
		java.io.OutputStream out;
		BufferedInputStream bis;
		BufferedOutputStream bos;
		path = ac.getRequestParameter("url");
		path = (new StringBuilder(String.valueOf(Path.getRootPath()))).append(
				path).toString();
		path = StringUtil.replace(path, "\\", "/");
		File obj = new File(path);
		if (!obj.exists() || !obj.isFile()) {
			ResponseWriter.write(response, "指定文件不存在！");
			return;
		}
		int index = path.lastIndexOf("/");
		String fileName = path.substring(index + 1);
		index = fileName.lastIndexOf(".");
		String extension = index >= 0 ? fileName.substring(index + 1) : "*";
		String contentType = MimeSettings.getContentType(extension);
		out = getOutputStream(response, fileName, contentType);
		bis = null;
		bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(path));
			bos = new BufferedOutputStream(out);
			byte buff[] = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
				bos.write(buff, 0, bytesRead);
		} catch (Exception exception) {
			if (bis != null)
				try {
					bis.close();
				} catch (Exception e) {
				}
			if (bos != null)
				try {
					bos.close();
				} catch (Exception e) {
				}
		}
	}
}
